package com.lazy.lib.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;


/**
 * @author lazy
 * @version 1.0
 * @created 2012-9-28 下午2:04:35
 */
public class ConfigUtil {
    private static Logger logger = LoggerFactory.getLogger(ConfigUtil.class);

	/**
	 * 读取配置
	 * 
	 * @param filePath
	 * @return
	 */
	public static Properties loadProperties(String filePath) {
		Properties properties = new Properties();
		return appendProperties(properties, filePath);
	}
	
	/**
	 * 将属性读取, 并追加到properties中
	 * @param properties
	 * @param filePath
	 * @return
	 */
    public static Properties appendProperties(Properties properties, String filePath) {
        InputStream inputStream = null;
        try {
            URL resource = ConfigUtil.class.getClassLoader().getResource(filePath);
            if (resource == null) {
                System.err.println("Failed load properties, file[" + filePath + "] not exists, please check it !!!!!!!!!\n");
                return properties;
            }
            inputStream = ConfigUtil.class.getClassLoader().getResourceAsStream(filePath);
            properties.load(inputStream);
            logger.info("load properties file[" + filePath + "]");
        } catch (IOException e) {
            System.err.println("Failed load properties file[" + filePath + "], please check it !!!!!!!!!\n");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e2) {
            }
        }

        return properties;
    }
	
    public static String getPrintString(Properties properties) {
        StringBuilder sb = new StringBuilder();
        for (Object key : properties.keySet()) {
            sb.append(key).append("=").append(properties.get(key)).append("\n");
        }
        
        return sb.toString();
    }
    
	private ConfigUtil() {
	}
	
	public static void main(String[] args) {
	    Properties properties = loadProperties("conf.properties");
		appendProperties(properties, "log4j.properties");
		// loadProperties("*.properties");
		
		System.out.println(getPrintString(properties));
	}
}
